﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Facebook;
using ThuPhap.Class;
using System.IO.IsolatedStorage;
using System.Windows.Controls.Primitives;
using ThuPhap.Controls;

namespace ThuPhap.Facebook
{
    public partial class LoginPage : PhoneApplicationPage
    {
        private const string ExtendedPermissions = "user_about_me,publish_stream";
        private readonly FacebookClient _fb = new FacebookClient();
        public string Filename { get; set; }
        private Popup popup;
        public LoginPage()
        {
            InitializeComponent();
            popup = new Popup() { Child = new LoadingControl("Connecting..."), IsOpen = true };
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string filename;
            if (NavigationContext.QueryString.TryGetValue("filename",out filename))
            {
                this.Filename = filename;
            }
        }
        
        private void BrowserControl_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            
            FacebookOAuthResult oauthResult;
            if ((e.Uri.AbsolutePath == "/login.php") || (e.Uri.AbsolutePath == "/connect/login_success.html"))
            {
                popup.IsOpen = false;    
            }

            
            if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
            {
                return;
            }

            if (oauthResult.IsSuccess)
            {
                popup.Child = new LoadingControl("Logining ...");
                popup.IsOpen = true;
                this.BrowserControl.Visibility = Visibility.Collapsed;
                var accessToken = oauthResult.AccessToken;
                LoginSucceded(accessToken);
            }
            else
            {
                MessageBox.Show(oauthResult.ErrorDescription);
            }
        }


        private void BrowserControl_Loaded(object sender, RoutedEventArgs e)
        {
            var parameters = new Dictionary<string, object>();
            parameters["client_id"] = FacebookSettings.AppID;
            parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
            parameters["response_type"] = "token";
            parameters["display"] = "page";
            parameters["scope"] = ExtendedPermissions;
            BrowserControl.Navigate(_fb.GetLoginUrl(parameters));
            
        }

        private void LoginSucceded(string accessToken)
        {
            var fb = new FacebookClient(accessToken);

            fb.GetCompleted += (o, e) =>
            {
                if (e.Error != null)
                {
                    Dispatcher.BeginInvoke(() => { MessageBox.Show(e.Error.Message); popup.IsOpen = false; });
                   
                    return;
                }

                var result = (IDictionary<string, object>)e.GetResultData();
                var id = (string)result["id"];

                SerializeHelper.SaveSetting<FacebookAccess>("FacebookAccess", new FacebookAccess
                {
                    AccessToken = accessToken,
                    UserId = id
                });
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    
                    NavigationService.Navigate(new Uri(string.Format("/Facebook/SharePage.xaml?id={0}&token={1}&filename={2}&type=login",id, accessToken, this.Filename), UriKind.Relative));
                    popup.IsOpen = false;
                });
            };

            
            fb.GetAsync("me?fields=id");
        }

        
    }
}